<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { User, Lock, ChatDotRound, Iphone, Notification } from '@element-plus/icons-vue'
import { getYzmApi, loginApi, getWxCodeApi } from '../api/Login.ts'
import { useUserMsgStore } from '@/stores/userMsg.ts';

const UserMsgStore = useUserMsgStore()
let loginDialogVisible = ref(false)
const changeDialogVisible = (x: boolean) => {
    loginDialogVisible.value = x
}

// 登录类型: 短信验证码登录/微信扫码登录
let loginType = ref('dxyzm')
const changeLoginType = async (x: string) => {
    loginType.value = x
    if (x === 'saoma') {
        //点击微信扫码登录|微信小图标切换为微信扫码登录
        // const changeScene = async () => {

        //发请求获取微信扫码二维码需要参数
        //咱们在想硅谷学校的服务器发请求,获取微信扫码登录页面参数
        //还需要携带一个参数:告诉学校服务器用户授权成功以后重定向项目某一个页面
        let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
        let res = await getWxCodeApi(redirect_URL);
        //生成微信扫码登录二维码页面
        //@ts-ignore
        new WxLogin({
            self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
            id: "login_weChat", //显示二维码容器设置
            appid: res.data.appid, //应用位置标识appid
            scope: "snsapi_login", //当前微信扫码登录页面已经授权了
            redirect_uri: res.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
            state: res.data.state, //state就是学校服务器重定向的地址携带用户信息
            style: "black",
            href: "",
        });
        // };
    }
}

let loginFormRef = ref()
const loginForm = ref({
    phoneNum: '',
    yzm: ''
})
const phonePattern = /^1[3-9]\d{9}$/
const loginFormRules = {
    phoneNum: [
        { required: true, message: '手机号必填', trigger: 'blur' },
        { pattern: phonePattern, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    yzm: [
        { required: true, message: '验证码必填', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]{6}$/, message: '验证码为6位字母或数字', trigger: 'blur' }
    ],
}
let canGetYzm = ref(false)
// 监听手机号输入框
let stopWatchPhone = watch(() => loginForm.value.phoneNum, (newVal) => {
    if (newVal.length === 11) {
        canGetYzm.value = phonePattern.test(newVal)
    }
})

// 当输入完手机号时才可以点击获取验证码
const getYzm = async () => {
    if (canGetYzm.value === true) {
        // console.log('可以获取验证码,调接口')
        const res = await getYzmApi(loginForm.value.phoneNum)
        loginForm.value.yzm = res.data
    }
}

const loginFun = async () => {
    await loginFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 调接口 登录成功后关闭窗口
            let res = await loginApi(loginForm.value.phoneNum, loginForm.value.yzm)
            UserMsgStore.setUserInfo(res.data.name, res.data.token)
            changeDialogVisible(false)
        } else {
            ElMessage.error('请检查输入是否正确')
            return false
        }
    })
}


defineExpose({ changeDialogVisible })
// 注销之前停止监听事件
onBeforeUnmount(() => {
    stopWatchPhone()
})
</script>

<template>
    <el-dialog v-model="loginDialogVisible" title="用户登录/注册" align-center draggable>
        <div class="login-container">
            <!-- 短信验证码登录模块 -->
            <div class="left-dxyzm" v-show="loginType === 'dxyzm'">
                <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
                    <el-form-item prop="phoneNum">
                        <el-icon>
                            <User />
                        </el-icon>
                        <el-input v-model="loginForm.phoneNum" placeholder='请输入手机号'></el-input>
                    </el-form-item>
                    <el-form-item prop="yzm">
                        <el-icon>
                            <Lock />
                        </el-icon>
                        <el-input type="yzm" v-model="loginForm.yzm" placeholder='请输入验证码'></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button :disabled="!canGetYzm" @click="getYzm">获取验证</el-button>
                    </el-form-item>
                    <p><el-button type="primary" @click="loginFun">用户登录</el-button></p>
                </el-form>
                <p @click="changeLoginType('saoma')" class="login-type">微信扫码登录
                    <el-icon>
                        <ChatDotRound />
                    </el-icon>
                </p>
            </div>
            <!-- 微信扫一扫登录模块 -->
            <div class="left-saoma" v-show="loginType === 'saoma'">
                <div id="login_weChat"></div>
                <!-- <img src="../assets/images/code_login_wechat.png" alt="扫码登录"> -->
                <p @click="changeLoginType('dxyzm')" class="login-type">手机短信验证码登陆
                    <el-icon>
                        <Iphone />
                    </el-icon>

                </p>
            </div>
            <!-- 其他生态 -->
            <div class="right-other">
                <dl>
                    <img src="../assets/images/code_app.png" alt="">
                    <el-icon>
                        <Notification />
                    </el-icon>
                    <dd>微信扫一扫关注“快速预约挂号”</dd>
                </dl>
                <dl>
                    <img src="../assets/images/code_app.png" alt="">
                    <el-icon>
                        <Notification />
                    </el-icon>
                    <dd>扫一扫下载“预约挂号”APP</dd>
                </dl>
                <h3>商医通官方指定平台 快速挂号 安全放心</h3>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="loginDialogVisible = false">关闭窗口</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
.login-container {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-dxyzm,
    .left-saoma,
    .right-other {
        width: 49%;

        p {
            text-align: center;
            margin: 10px 0;
            cursor: pointer;
        }
    }

    .left-dxyzm {
        border: 1px solid var(--border-color);

        .el-form {
            margin-top: 20px;
        }

        :deep(.el-form-item__content) {
            margin: 0 10px !important;

            .el-input__inner {
                padding-left: 20px;
            }

            .el-icon {
                color: var(--info-color);
                position: absolute;
                /* input输入框高度32 icon图标高度就是root字体14px (32-14)/2=9 */
                top: 10px;
                left: 10px;
                z-index: 1;
            }
        }
    }

    .left-saoma {
        img {
            width: 90%;
        }
    }

    .right-other {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        dl {
            width: 48%;

            img {
                width: 100%;
            }

            dd {
                margin-top: 6px;
            }
        }

        h3 {
            margin-top: 20px;
            font-size: 20px;
            padding: 0 14px;
            text-align: center;
        }
    }
}
</style>